import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat_app_project/const/sys_const.dart';
import 'package:chat_app_project/dao/demand_dao.dart';
import 'package:chat_app_project/models/demand_entity.dart';
import 'package:chat_app_project/models/page_info_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../components/customer_waterdrop_header.dart';
import 'detail/detail.dart';

class Index extends StatefulWidget {
  const Index({Key? key}) : super(key: key);

  @override
  State<Index> createState() => _IndexState();
}

class _IndexState extends State<Index> {
  // 图片数组
  List<DemandEntity> dataList = [];

  @override
  void initState() {
    super.initState();
  }

  final RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  var _page = 1;
  var _pageSize = 10;

  void _onLoading() async {
    debugPrint("_onLoading---------------");
    // monitor network fetch
    // await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    // items.add((items.length+1).toString());
    if (mounted) {
      _page += 1;
      _getData();
    }
    _refreshController.loadComplete();
  }

  void _onRefresh() async {
    debugPrint("_onRefresh---------------");
    _page = 1;
    _getData();
  }

  void _getData() async {
    // monitor network fetch
    // await Future.delayed(const Duration(milliseconds: 1000));
    if (_page == 1) {
      dataList.clear();
    }
    //重置加载无数据状态->可加载
    _refreshController.resetNoData();
    // dataList.add(
    //     "https://up.enterdesk.com/edpic_source/ea/e5/2b/eae52b8bd88c068cd4f782914f809271.jpg");
    // dataList.add(
    //     "https://img1.baidu.com/it/u=2252911813,3770214976&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=750");
    // dataList.add(
    //     "https://img0.baidu.com/it/u=3872472310,59117006&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=1280");
    // dataList.add(
    //     "https://up.enterdesk.com/edpic_source/ac/aa/f2/acaaf2ccea32a116ea51390ceb6ce3c7.jpg");
    if (_refreshController.isLoading) {
      _refreshController.loadComplete();
    } else if (_refreshController.isRefresh) {
      _refreshController.refreshCompleted();
    }
    setState(() {});

    DemandDao.recommend({ "pageNum": _page, "pageSize": _pageSize})
        .then((value) {
        var pageInfo = PageInfoEntity.fromJson(value.data);
        for (var element in pageInfo.list) {
          dataList.add(DemandEntity.fromJson(element));
        }
        if (dataList.length < pageInfo.total) {
          if (_refreshController.isLoading) {
            _refreshController.loadComplete();
          } else if (_refreshController.isRefresh) {
            _refreshController.refreshCompleted();
          }
        }
        if (dataList.length >= pageInfo.total) {
          if (_refreshController.isLoading) {
            _refreshController.loadNoData();
          } else if (_refreshController.isRefresh) {
            _refreshController.refreshToIdle();
          }
        }
        setState(() { });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("首页"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(2.0),
        child: refresher(MasonryGridView.count(
          crossAxisCount: 2,
          mainAxisSpacing: 8.0,
          crossAxisSpacing: 8.0,
          itemCount: dataList.length,
          itemBuilder: (BuildContext context, int index) {
            return itemWidget(context, index);
          },
        )),
      ),
    );
  }

  Widget refresher(Widget body) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: const CustomerWaterDropHeader(),
      footer: CustomFooter(
        builder: (context, mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = const Text("上拉刷新");
          } else if (mode == LoadStatus.loading) {
            body = const CupertinoActivityIndicator();
          } else if (mode == LoadStatus.failed) {
            body = const Text("加载失败!点击重试!");
          } else if (mode == LoadStatus.canLoading) {
            body = const Text("释放加载更多");
          } else {
            body = const Text("没有更多数据");
          }
          return SizedBox(
            height: 55.0,
            child: Center(child: body),
          );
        },
      ),
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: body,
    );
  }

  // 瀑布流每个子项
  Widget itemWidget(context, int index) {
    debugPrint("长度 ${dataList.length}  下标 $index");
    DemandEntity demandEntity = dataList[index];
    return Column(
      children: [
        picWidget(demandEntity),
        infoWidget(demandEntity),
      ],
    );
    //   Material(
    //   elevation: 8.0,
    //   borderRadius: const BorderRadius.all(
    //     Radius.circular(8.0),
    //   ),
    //   child: ,
    // );
  }

  Widget picWidget(DemandEntity demandEntity){
    return InkWell(
      child: Hero(
          tag: demandEntity.content,
          child: Stack(
            children: [
              CachedNetworkImage(
                imageUrl: demandEntity.pics[0],
                fit: BoxFit.fitWidth,
              )
            ],
          )),
      onTap: () {
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => DemandDetail(demandEntity: demandEntity,)));
      },
    );
  }

  Widget infoWidget(DemandEntity demandEntity) {
    return   Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Padding(padding: EdgeInsets.all(4.0)),
        Row(
          children: [
            CircleAvatar(
              radius: 15,
              backgroundImage: NetworkImage(demandEntity.memberInfo.avatar),
            ),
            const Padding(
              padding: EdgeInsets.only(left: 8.0),
            ),
            Text(demandEntity.memberInfo.nickName),
          ],
        ),
        const Padding(padding: EdgeInsets.all(2.0)),
        Text(
          demandEntity.content,
          //超出隐藏
          overflow: TextOverflow.ellipsis,
        ),
        const Padding(padding: EdgeInsets.all(2.0)),
      ],
    );
  }
}
